<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/12/22
 * Time: 14:51
 */
namespace common\components\extenders;

use yii\base\Component;
use yii\base\ErrorException;
use yii\helpers\ArrayHelper;

class SmsSend extends Component
{
    public $url = 'http://106.ihuyi.cn/webservice/sms.php?method=Submit';//sms提交接口

    public $account;

    public $password;


    public function init()
    {
        parent::init();
        if (empty($this->account) || empty($this->password)) throw new ErrorException('请设置账户密码');
    }

    public function send($data)
    {
        if (!ArrayHelper::keyExists('mobile', $data)) throw new ErrorException('手机号码不能为空');
        if (!ArrayHelper::keyExists('content', $data)) throw new ErrorException('发送内容不能为空');
        $mobile = $data['mobile'];
        $post_data = "account=" . $this->account .
            "&password=" . $this->password .
            "&mobile=" . $mobile .
            "&content=" . rawurlencode($data['content']);
        $gets = self::xmlToArray(self::httpPost($this->url, $post_data));
        /*\Yii::error("------------start: 发送短信返回内容----------");
        \Yii::error($gets);
        \Yii::error("------------end: 发送短信返回内容----------");*/
        return $gets['SubmitResult'];
    }

    /*
     * http POST 请求
     * $url:API地址
     * $data:POST提交的数据
     * */
    private static function httpPost($url, $data)
    {
        $curl = curl_init();//初始化一个curl会话,返回一个curl句柄,供curl_setopt(), curl_exec()和curl_close() 函数使用
        curl_setopt($curl, CURLOPT_URL, $url);//要提交到哪个网址
        curl_setopt($curl, CURLOPT_HEADER, false);//设置头部包含在输出中
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//value为true表示直接输出结果
        curl_setopt($curl, CURLOPT_NOBODY, true);//设置输出中包含body部分
        curl_setopt($curl, CURLOPT_POST, true);//启动时会发送一个常规的POST请求,就像表单提交的一样
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);//全部数据使用HTTP协议的POST操作来发送
        $return_str = curl_exec($curl);//执行给定的cURL会话。
        curl_close($curl);////关闭给定的cURL会话。
        return $return_str;
    }

    private static function xmlToArray($xml)
    {
        $arr = [];
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if (preg_match_all($reg, $xml, $matches)) {
            $count = count($matches[0]);
            for ($i = 0; $i < $count; $i++) {
                $subxml = $matches[2][$i];
                $key = $matches[1][$i];
                if (preg_match($reg, $subxml)) {
                    $arr[$key] = self::xmlToArray($subxml);
                } else {
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }
}